<template>
  <el-form :model="form" ref="formRef" :rules="rules" inline-message>
    <el-table :data="tableData">
      <!-- {{ props.modelData.columns }} -->
      <el-table-column v-for="item of props.modelData.columns.filter(x => !x.hidden)" align="center" :label="item.label"
        :prop="item.field" :width="item.width ?? ''">
        <template #default="scope">
          <el-form-item :prop="`${item.field}-${scope.$index}`">
            <el-date-picker v-if="item.type === FORM_FIELD_TYPE.DATE" :type="item.type"
              @update:model-value="(v) => form[`${item.field}-${scope.$index}`] = v"
              v-model="tableData[scope.$index][item.field]" value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
            <template v-else-if="item.type === FORM_FIELD_TYPE.SINGLE_LAYER_SELECT">
              <!-- {{ item.options }} -->
              <SingleLayerSelect :options="item.options" :disabled="item.disabled"
                v-model="tableData[scope.$index][item.field]"
                @update:model-value="(v) => handleSelectChange(v, item, scope.$index)" />
            </template>
            <component v-else-if="item.render" v-model="tableData[scope.$index][item.field]"
              :is="item.render({ handlers: { updateParam: (key: any, value: any) => updateParam(scope.$index, key, value) } })">
            </component>
            <RemoteSearchSelect v-else-if="item.type === FORM_FIELD_TYPE.REMOTESEARCH"
              v-model="tableData[scope.$index][item.field]" placeholder="请输入供应商名称进行搜索" :remoteSearch="item.remoteSearch"
              @update:model-value="(v) => handleSelectChange(v, item, scope.$index)" />
            <el-input @update:model-value="(v) => form[`${item.field}-${scope.$index}`] = v"
              :disabled="item.config && item.config.disabled !== undefined ? item.config.disabled : false"
              v-model="tableData[scope.$index][item.field]"
              @update:modelValue="(v: any) => item.callback && item.callback({ updateParam: (key: any, value: any) => updateParam(scope.$index, key, value) }, tableData[scope.$index], v)"
              v-else />
          </el-form-item>
        </template>
      </el-table-column>
      <el-table-column v-if="props.modelData.delApi && props.modelData.delParamKey">
        <template #default="{ row, $index }">
          <el-popconfirm title="是否确认删除？">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
            <template #actions="{ confirm, cancel }">
              <el-button size="small" @click="cancel">取消</el-button>
              <el-button type="danger" size="small" @click="() => handleDelete(row, $index)">
                确认
              </el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
  </el-form>
  <el-button class="mt-4" type="primary" style="width: 100%" @click="onAddItem">
    新增
  </el-button>
</template>

<script setup lang="ts">
import { FormRules } from "element-plus";
import FORM_FIELD_TYPE from "/@/constants/FormFieldType.ts";
const props = defineProps<{
  modelData: { data: any[], columns: any[]; requestData: { api: any }, delApi: (data: any) => void, delParamKey: any };
}>();

const formRef = useTemplateRef("formRef")
const form = reactive<Record<any, any>>({})
const model = defineModel()
const tableData = ref<any[]>([]);
const rules = ref<FormRules>({})

onMounted(() => {
  console.log("editable modlel data :", props.modelData.data);

  console.log("model value ", model.value);

  tableData.value = props.modelData.data ?? []
  model.value = props.modelData.data
  generateRules()
})

const handleSelectChange = (v, item, index) => {
  if (item.callback) {
    item.callback(v)
  }
  console.log("select change", v, item, index)
  form[`${item.field}-${index}`] = v
}

const generateRules = () => {
  props.modelData.columns.forEach(x => {
    tableData.value.forEach((_, index) => {
      rules.value[`${x.field}-${index}`] = x.rule
    })
  })
  console.log("rules", rules.value)
}

watch(() => props.modelData.columns, () => { }, { deep: true })
watch(() => model.value, (v) => {
  console.log("modelValue", v)
  tableData.value = v
  generateRules()
})

watch(() => props.modelData.data, (v) => {
  tableData.value = v
  model.value = v
  v.forEach((x, index) => {
    for (const key of Object.keys(x)) {
      form[`${key}-${index}`] = x[key]
    }
  })
  console.log("form", form)
})

watch(() => tableData.value, (v) => {
  model.value = v
  generateRules()
})

const onAddItem = () => {
  const obj = {}
  for (const item of props.modelData.columns) {
    obj[item.field] = item.defaultValue ?? ""
    if (item.defaultValue) {
      form[`${item.field}-${tableData.value.length}`] = item.defaultValue
    }
  }
  tableData.value.push(obj)
  generateRules()
}
const handleDelete = (row, index) => {
  console.log("del row", row)
  tableData.value.splice(index, 1)
  if (row.id && row.id !== 0) {
    props.modelData.delApi({ [props.modelData.delParamKey]: row.id })
  }
}

function updateParam(index: any, key: any, value: any) {
  tableData.value[index][key] = value
}

defineExpose({
  tableData,
  validate: computed(() => formRef.value?.validate)
})
</script>

<style scoped></style>
